package com.jyw.system.utils;

import com.jyw.common.constant.CacheConstants;
import com.jyw.common.core.domain.entity.SysDept;
import com.jyw.common.core.redis.RedisCache;
import com.jyw.common.utils.StringUtils;
import com.jyw.common.utils.spring.SpringUtils;
import com.jyw.system.domain.SysTeam;
import com.jyw.system.service.ISysDeptService;
import com.jyw.system.service.ISysTeamService;
import org.springframework.util.ObjectUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author 沈峻
 * @ClassName DeptUtils
 * @Description 科室工具类
 * @Date 2023/8/24 17:41
 **/
public class TeamUtils {

    /**
     * 小组ID转小组名称
     * @param teamId 小组ID (可以是字符串 1,2,3 也可以是Long类型)
     * @return
     */
    public static String teamIdToName(Object teamId){
        if(ObjectUtils.isEmpty(teamId)){
            return null;
        }
        List<SysTeam> list = cacheList();
        //判断用户Id是否为字符串
        if(teamId instanceof String){
            String idStr = (String) teamId;
            if(!StringUtils.isEmpty(idStr)){
                return Arrays.stream(idStr.split(",")).map(data -> {
                    Optional<SysTeam> optional = list.stream().filter(team -> team.getId().toString().equals(data)).findFirst();
                    if (optional.isPresent()) {
                        return optional.get().getTeamName();
                    } else {
                        return data;
                    }
                }).collect(Collectors.joining(","));
            }
        } else if (teamId instanceof Long) {
            Long idL = (Long) teamId;
            Optional<SysTeam> optional = list.stream().filter(team ->team.getId().equals(idL)).findFirst();
            if (optional.isPresent()){
                return optional.get().getTeamName();
            }else{
                return idL.toString();
            }
        }
        return null;
    }

    /**
     * 清除小组工具类使用的小组缓存
     */
    public static void cleanCache(){
        getRedisCache().deleteObject(CacheConstants.TEAM_CACHE_KEY);
    }

    /**
     * 获取小组列表缓存
     */
    public static List<SysTeam> cacheList(){
        RedisCache redisCache = getRedisCache();
        if (redisCache.hasKey(CacheConstants.TEAM_CACHE_KEY)) {
            //存在小组缓存列表
            return redisCache.getCacheList(CacheConstants.TEAM_CACHE_KEY);
        }else {
            //从数据库中索引
            List<SysTeam> list = getTeamService().list();
            redisCache.setCacheList(CacheConstants.TEAM_CACHE_KEY,list);
            return list;
        }
    }

    /**
     * 获取小组接口服务
     * @return
     */
    private static ISysTeamService getTeamService(){
        return SpringUtils.getBean(ISysTeamService.class);
    }
    /**
     * 获取Redis操作对象
     */
    private static RedisCache getRedisCache(){
        return SpringUtils.getBean(RedisCache.class);
    }
}
